package org.zjx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.zjx.dao.entity.DailyTasks;
import org.zjx.dao.entity.DeviceDailyTask;
import org.zjx.dao.entity.Role;
import org.zjx.dao.mapper.DailyTasksMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.zjx.service.IDailyTasksService;
import org.zjx.service.IDeviceDailyTaskService;
import org.zjx.service.IDeviceService;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 
 * @since 2025-05-28
 */
@Service
public class DailyTasksServiceImpl extends ServiceImpl<DailyTasksMapper, DailyTasks> implements IDailyTasksService {
    @Autowired
    private IDeviceDailyTaskService deviceDailyTaskService;

    @Override
    public DailyTasks queryTasksOnAccountUnUsd() {
        QueryWrapper<DailyTasks> wrapper = new QueryWrapper<>();
        // 无需额外条件，基础条件已在XML中定义

        List<DailyTasks> dailyTasks = getBaseMapper().queryTasksOnAccountUnUsd(wrapper);
        return dailyTasks.isEmpty() ? null : dailyTasks.get(0);
    }


    @Override
    public DailyTasks selectByConditions(long deviceId, int temporary) {
        DeviceDailyTask deviceDailyTask = deviceDailyTaskService.selectByConditions(deviceId, temporary);
        if (deviceDailyTask == null) return null;
        DailyTasks dailyTasks = getBaseMapper().selectById(deviceDailyTask.getDailyTasksId());
        if (dailyTasks == null || dailyTasks.getStatus() < 2) return null;
        return dailyTasks;
    }

    @Override
    public boolean updateByConditions(long daily_task_id) {
        return lambdaUpdate()
                .set(DailyTasks::getStatus, 3)
                .eq(DailyTasks::getId, daily_task_id)
                .update();  // 注意：LambdaUpdate做复杂更新时，最后必须记得加上.update()进行更新操作
    }

    @Override
    public boolean dailyTaskOver(long daily_task_id, long deviceId, int temporary) {
        if (daily_task_id == 0 || deviceId == 0) return false;

        QueryWrapper<DeviceDailyTask> wrapper = new QueryWrapper<>();
        wrapper.eq("temporary", temporary)      // 设备任务临时标识
                .eq("device_id", deviceId)
                .eq("daily_tasks_id",daily_task_id);                     // 任务状态为3


        DeviceDailyTask deviceDailyTask = deviceDailyTaskService.getOne(wrapper);
        if (deviceDailyTask == null) return false;
        deviceDailyTaskService.removeById(deviceDailyTask.getId());
        return true;
    }

    @Override
    public DailyTasks queryTaskByRole(Role role) {
        return null;
    }
}
